import { useState } from "react";
import "./assets/css/style.css";
import NewTodoForm from "./NewTodoForm";
import TodoList from "./TodoList";

export default function App() {
  const [newItem, setNewItem] = useState("");
  const [todos, setTodos] = useState([]);

  const handleSubmit = (e) => {
    e.preventDefault();

    setTodos((current) => [
      ...current,
      { id: crypto.randomUUID(), title: newItem, completed: false },
    ]);

    setNewItem("");
  };

  const toggleTodo = (id, completed) => {
    setTodos((current) => {
      return current.map((todo) => {
        if (todo.id === id) {
          return { ...todo, completed };
        }
        return todo;
      });
    });
  };

  const deleteTodo = (id) => {
    setTodos((current) => {
      return current.filter((todo) => todo.id !== id);
    });
  };

  return (
    <>
      <NewTodoForm
        newItem={newItem}
        setNewItem={setNewItem}
        handleSubmit={handleSubmit}
      />
      <TodoList todos={todos} toggleTodo={toggleTodo} deleteTodo={deleteTodo} />
    </>
  );
}
